package com.stock.publiclib;

import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.stock.publiclib.adapter.SimpleViewPagerAdapter;
import com.stock.publiclib.utils.StringUtil;

import java.util.ArrayList;
import java.util.List;

import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;


/**
 * ---------------------------------------------------
 * Description: 基于drawerlayout+CoordinatorLayout+toolbar+tablayout+viewpaer的基类
 * Author: ljgsonx
 * Belong to: com.stock.publiclib
 * Time: 2016/1/20 11:56
 * ---------------------------------------------------
 */
public class BaseActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener, View.OnClickListener {

    LayoutInflater mInflater;

    public final static int ACTIVITY_MODE_NORMAL = 0;
    public final static int ACTIVITY_MODE_VIEWPAGER = 1;

    private int activityType = ACTIVITY_MODE_NORMAL;

    private DrawerLayout mDrawerLayout;
    private CoordinatorLayout mCoordinatorLayout;
    private AppBarLayout mAppBarLayout;
    private Toolbar mToolbar;
    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private FrameLayout mFrameLayout;
    private NavigationView mNavigationView;
    private View mNaviHeader;
    private View mNaviMenu;

    private LinearLayout mFrameLinearLayout;

    private ProgressDialog progressDialog;

    // TabLayout中的tab标题
    private String[] mTitles;
    // 填充到ViewPager中的Fragment
    private List<Fragment> mFragments;
    // ViewPager的数据适配器
    private SimpleViewPagerAdapter mViewPagerAdapter;

    private PopupWindow mLoadingPop;

    private int mTabLayoutPaddingTop;

    private long exitTime = 0;

    AppBarLayout.OnOffsetChangedListener mOnOffsetChangedListener = new AppBarLayout.OnOffsetChangedListener() {

        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
            int maxScrollRange = appBarLayout.getTotalScrollRange();
            float scrollRate = Math.abs((float) verticalOffset/maxScrollRange);
            if(null != mTabLayout)
                mTabLayout.setPadding(0, (int) (scrollRate * mTabLayoutPaddingTop), 0, 0);
        }
    };

    private OnPageSelectedListener mOnPageSelectedListener;

    public void setmOnPageSelectedListener(OnPageSelectedListener onPageSelectedListener) {
        this.mOnPageSelectedListener = onPageSelectedListener;
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (mOnPageSelectedListener != null) {
            mOnPageSelectedListener.OnPageSelected(position);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void setContentView(View view) {
        initAll();
        //mLinearLayout.addView(view);
        if(activityType == ACTIVITY_MODE_VIEWPAGER)
            super.setContentView(mDrawerLayout);
        else
            super.setContentView(mFrameLinearLayout);
    }

    private void initAll(){
        mInflater = LayoutInflater.from(this);
        initViews();
        initData();
        configViews();
    }

    private void initViews() {
        if (activityType == ACTIVITY_MODE_VIEWPAGER) {
            mDrawerLayout = (DrawerLayout)mInflater.inflate(R.layout.base_activity_viewpager, null);
            mNavigationView = (NavigationView) mDrawerLayout.findViewById(R.id.id_navigationview);
            mCoordinatorLayout = (CoordinatorLayout) mDrawerLayout.findViewById(R.id.id_coordinatorlayout);
            mAppBarLayout = (AppBarLayout) mDrawerLayout.findViewById(R.id.id_appbarlayout);
            mToolbar = (Toolbar) mDrawerLayout.findViewById(R.id.id_toolbar);
            mTabLayout = (TabLayout) mDrawerLayout.findViewById(R.id.id_tablayout);
            mViewPager = (ViewPager) mDrawerLayout.findViewById(R.id.id_viewPager);
        }else {
            mFrameLinearLayout = (LinearLayout) mInflater.inflate(R.layout.content_framelayout, null);
            mToolbar = (Toolbar) mFrameLinearLayout.findViewById(R.id.id_toolbar);
            mFrameLayout = (FrameLayout) mFrameLinearLayout.findViewById(R.id.id_baseFrame);
        }
    }

    //如果子类未给予tab title和 fragments,则使用默认的
    private void initData() {

        //获得资源中tablayout的padding top
        mTabLayoutPaddingTop = getResources().getDimensionPixelSize(R.dimen.tablayout_padding_top);
        // Tab的标题采用string-array的方法保存，在res/values/arrays.xml中写
        if((mTitles == null || mFragments == null) && activityType == ACTIVITY_MODE_VIEWPAGER) {
            mTitles = getResources().getStringArray(R.array.tab_titles_default);
            mFragments = new ArrayList<>();
            for (int i = 0; i < mTitles.length; i++) {
                Bundle mBundle = new Bundle();
                mBundle.putInt("flag", i);
                SimpleFragment mFragment = new SimpleFragment();
                mFragment.setArguments(mBundle);
                mFragments.add(i, mFragment);
            }
        }
    }

    private void configViews() {
        // 设置显示Toolbar
        setSupportActionBar(mToolbar);

        mToolbar.setTitle("");

        if (activityType == ACTIVITY_MODE_VIEWPAGER) {
            // 设置Drawerlayout开关指示器，即Toolbar最左边的那个icon
            ActionBarDrawerToggle mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.open, R.string.close);
            mActionBarDrawerToggle.syncState();
            mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);

            //给NavigationView填充顶部区域，也可在xml中使用app:headerLayout="@layout/header_nav"来设置
            mNaviHeader = mNavigationView.inflateHeaderView(R.layout.header_nav);
            //给NavigationView填充Menu菜单，也可在xml中使用app:menu="@menu/menu_nav"来设置
            mNavigationView.inflateMenu(R.menu.menu_nav);

            // 初始化ViewPager的适配器，并设置给它
            mViewPagerAdapter = new SimpleViewPagerAdapter(getSupportFragmentManager(), mTitles, mFragments);
            mViewPager.setAdapter(mViewPagerAdapter);
            // 设置ViewPager最大缓存的页面个数,默认为1,设为0无效,等同于1
            mViewPager.setOffscreenPageLimit(4);
            // 给ViewPager添加页面动态监听器（为了让Toolbar中的Title可以变化相应的Tab的标题）
            mViewPager.addOnPageChangeListener(this);

            //mTabLayout.setTabMode(MODE_SCROLLABLE);
//            mTabLayout.setTabMode(TabLayout.MODE_FIXED);
            // 将TabLayout和ViewPager进行关联，让两者联动起来
            mTabLayout.setupWithViewPager(mViewPager);
            // 设置Tablayout的Tab显示ViewPager的适配器中的getPageTitle函数获取到的标题
            mTabLayout.setTabsFromPagerAdapter(mViewPagerAdapter);

            //适配toolbar隐藏的高度,调整tablayout的padding top
            mAppBarLayout.addOnOffsetChangedListener(mOnOffsetChangedListener);
        }

        //沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
            if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
                if(mDrawerLayout != null){
                    //将侧边栏顶部延伸至status bar
                    mDrawerLayout.setFitsSystemWindows(true);
                    //将主页面顶部延伸至status bar;虽默认为false,但经测试,DrawerLayout需显示设置
                    mDrawerLayout.setClipToPadding(false);
                }else{
                    //设置后,会出现打开输入法,拉长toolbar的bug
                    //mToolbar.setFitsSystemWindows(true);
                    //默认即为false,可以不设置
                    mToolbar.setClipToPadding(false);
                }
            }
        }
    }

    public void setToolbarPosTitle(String title) {
        TextView tv = (TextView) mToolbar.findViewById(R.id.posTtitleTv);
        tv.setText(title);
    }

    public void setToolbarSubTitle(String title) {
        TextView tv = (TextView) mToolbar.findViewById(R.id.subTitleTv);
        tv.setVisibility(View.VISIBLE);
        tv.setText(title);
    }

    public TextView getToolbarMenu() {
        TextView tv = (TextView) mToolbar.findViewById(R.id.app_menuBtnTv);
        return tv;
    }

    public void removeToolbarMenu() {
        mToolbar.removeView(mToolbar.findViewById(R.id.app_menuBtnTv));
    }

    public TabLayout getTabLayout() {
        return mTabLayout;
    }

    public void setOnNavigationItemClicked(NavigationView.OnNavigationItemSelectedListener listener){
        mNavigationView.setNavigationItemSelectedListener(listener);
    }

    protected void setFragmentsWithTabs(List<Fragment> fragments,String[] tabTitles){
        this.activityType = ACTIVITY_MODE_VIEWPAGER;
        this.mFragments = fragments;
        this.mTitles = tabTitles;
        setContentView(null);
    }

    public void addFragment(Fragment fragment) {
        setContentView(null);
        getSupportFragmentManager().beginTransaction()
                .setCustomAnimations(R.anim.in_from_right, R.anim.out_from_left,
                        R.anim.in_from_left, R.anim.out_from_right)
                .replace(R.id.id_baseFrame, fragment)
                .addToBackStack(null).commit();
    }

    public void setFragmentContentView(View view) {
        setContentView(null);
        ViewGroup vg = (ViewGroup) findViewById(R.id.id_baseFrame);
        vg.addView(view);
    }

    @Override
    public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        } else if((System.currentTimeMillis()-exitTime)>2000) {
            Toast.makeText(this, "再按一次退出程序!", Toast.LENGTH_LONG).show();
            exitTime = System.currentTimeMillis();
        }else{
            super.onBackPressed();
        }
    }

    public ViewPager getViewPager() {
        return mViewPager;
    }
    public DrawerLayout getDrawerLayout() {
        return mDrawerLayout;
    }

    protected void setNaviUserName(String userName) {
        TextView tv = (TextView) mNaviHeader.findViewById(R.id.id_header_authorname);
        tv.setText(userName);
    }

    public void startPopLoading(View parentView) {
        startPopLoading(parentView, null);
    }

    public void startPopLoading(View parentView,String loadingTip) {
        View loadingView = LayoutInflater.from(this).inflate(R.layout.loading, null);
        if(!StringUtil.isBlank(loadingTip)) {
            TextView tv = (TextView) loadingView.findViewById(R.id.loadTipTv);
            tv.setText(loadingTip);
        }
        mLoadingPop = new PopupWindow(loadingView, ActionBar.LayoutParams.WRAP_CONTENT,
                ActionBar.LayoutParams.WRAP_CONTENT, false);
        mLoadingPop.showAtLocation(parentView, Gravity.CENTER, 0, 0);
    }

    public void startPopLoadingByPacMan(View parentView) {
        startPopLoadingByPacMan(parentView, null);
    }

    public void startPopLoadingByPacMan(View parentView,String loadingTip) {
        View loadingView = LayoutInflater.from(this).inflate(R.layout.loading_mouse, null);
        if(!StringUtil.isBlank(loadingTip)) {
            TextView tv = (TextView) loadingView.findViewById(R.id.loadTipTv);
            tv.setText(loadingTip);
        }
        mLoadingPop = new PopupWindow(loadingView, ActionBar.LayoutParams.WRAP_CONTENT,
                ActionBar.LayoutParams.WRAP_CONTENT, false);
        mLoadingPop.showAtLocation(parentView, Gravity.CENTER, 0, 150);
    }

    public void stopPopLoading() {
        if (null != mLoadingPop && mLoadingPop.isShowing()) {
            mLoadingPop.dismiss();
        }
    }

    public void showProgress(final String title) {
        if (!isProgress()) {
            ProgressDialog progressDialog = new ProgressDialog(this);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.process_dialog_clockwise));
            progressDialog.setCancelable(true);
            if (!TextUtils.isEmpty(title)) {
                progressDialog.setMessage(title);
            }
            progressDialog.show();
            this.progressDialog = progressDialog;
        }
    }

    public void stopProgress() {
        if (isProgress()) {
            progressDialog.dismiss();
        }
    }

    public boolean isProgress() {
        return progressDialog != null && progressDialog.isShowing();
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

    public interface OnPageSelectedListener{
        void OnPageSelected(int position);
    }
}
